package com.blensmile.testvido

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import com.blensmile.ffmpeglib.FFUtils
import com.blensmile.testvido.utils.FileUtils
import com.blensmile.testvido.utils.LogUtils
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.StringBuilder
import java.util.ArrayList

class MainActivity : AppCompatActivity(),View.OnClickListener{


    private var videoPath:String? = null
    private var cover:String?=null
    private var des:String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        checkPermission(arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ),100)

        //arm64-v8a, armeabi-v7a,armeabi
        if(android.os.Build.VERSION.SDK_INT<21) {
            LogUtils.b(android.os.Build.CPU_ABI)
            LogUtils.b(android.os.Build.CPU_ABI2)
        }else {
            var a = Build.SUPPORTED_ABIS;
            for(b in a){
                LogUtils.b(b)
            }
        }
//        VideoSDK.initSDK( FileUtils.getJadeCache().toString(), FileUtils.getJadeDCIM().toString());
//        CBUtils.init()
    }

    protected fun checkPermission(permission: Array<String>, requestCode: Int): Boolean {
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                val list = ArrayList<String>()
                for (p in permission) {
                    if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(applicationContext, p)) {
                        list.add(p)
                    }
                }
                if (list.size>0) {
                    val a = arrayOfNulls<String>(list.size)
                    ActivityCompat.requestPermissions(this, list.toArray(a), requestCode)
                    return false
                }
            } catch (e: Exception) {
                return false
            }

        }
        return true
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onClick(v: View?) {
        when(v?.id){
//            R.id.imgPlay->{
//                if(!videoPath.isNullOrEmpty()) {
//                    val inten = Intent(this, VideoActivity::class.java)
//                    inten.putExtra("url", videoPath)
//                    startActivity(inten)
//                }
//            }
//            R.id.btShot->{
////                VideoSDK.initSDK( FileUtils.getJadeCache().toString(), FileUtils.getJadeDCIM().toString());
////                CBUtils.init()
////                val intent = Intent(this,VideoRecorderActivity::class.java)
//                val intent = Intent(this,MediaRecorderActivity::class.java)
//                startActivityForResult(intent,100)
//            }
            R.id.btSelect->{
                selectVideo()
            }
//            R.id.tvJx->{
//                if(!TextUtils.isEmpty(videoPath)){
//                    //生成图片
//                    val cmd = etCmd.text.toString()
//                    LogUtils.b(cmd)
//                    FFmpegBridge.jxFFmpegCMDRun(cmd)
//                    ImageLoader.showOrFile(this,imgPlay,des,R.drawable.def_cover);
//                }
//            }
//            R.id.tvCB->{
//                LogUtils.b("tvCB clicked")
//                if(!TextUtils.isEmpty(videoPath)){
//                    //生成图片
//                    val cmd = etCmd.text.toString()
//                    LogUtils.b(cmd)
////                    LogUtils.b("ffpegCode:"+FFmpegUtils.run(cmd))
////                    ImageLoader.showOrFile(this,imgPlay,des,R.drawable.def_cover);
//                }
//            }
            R.id.btInit->{
                FFUtils.init()
            }
            R.id.btCb->{
                LogUtils.b("tvCB clicked")
                if(!TextUtils.isEmpty(videoPath)){
                    //生成图片
                    val cmd = etCmd.text.toString()
                    LogUtils.b(cmd)
                    LogUtils.b("ffpegCode:"+ FFUtils.run(cmd))
//                    ImageLoader.showOrFile(this,imgPlay,des,R.drawable.def_cover);
                }
            }
            R.id.btCmd->{
                etCmd.setText( getCMD() )
            }
        }
    }

    fun getCMD():String {
        val ss = " -ss 1 "
        des = getPath().append(System.currentTimeMillis()).append(".jpg").toString();
        return String.format(
            "ffmpeg  -i  %s %s -f image2  %s ",
            videoPath,
            ss,
            des
        )
    }

    fun getPath():StringBuilder {
        return FileUtils.getJadeDCIM();
    }//    fun getCaptureThumbnailsCMD(videoPath: String, outputPath: String, ss: String?): Boolean {
//        var ss = ss
//        if (ss == null)
//            ss = ""
//        else
//            ss = " -ss $ss"
//        return FFmpegBridge.jxFFmpegCMDRun(
//            String.format(
//                "ffmpeg  -i  %s %s -vframes 1  %s ",
//                videoPath,
//                ss,
//                outputPath
//            )
//        ) == 0
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK && requestCode == 100 && data!=null){
//            intent.putExtra("video", data.getStringExtra("videoPath"))
//            intent.putExtra("cover", data.getStringExtra("cover"))
            videoPath = data.getStringExtra("video")
            cover = data.getStringExtra("cover")
//            if(!cover.isNullOrEmpty()){
//                //显示图片
//                ImageLoader.showOrFile(this,imgPlay,cover,R.drawable.def_cover);
//            }
            tvInfo.setText(videoPath)
        }else if(resultCode == Activity.RESULT_OK && requestCode == 1001){
            val uri = data?.getData()
            videoPath = uri?.toString()
            if(videoPath!=null) {
                if (videoPath!!.startsWith("content://")) {
                    videoPath =
                            FileUtils.getPathByUri4kitkat(
                                this,
                                uri
                            )
                } else if (videoPath!!.startsWith("file://")) {
                    videoPath = videoPath!!.substring(7)
                }
                tvInfo.setText(videoPath)
            }
        }
    }

    fun selectVideo(){
        val intent = Intent()
        intent.type = "video/*" //选择视频 （mp4 3gp 是android支持的视频格式）
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(intent, 1001)
    }
}
